package com.example.demo.pattern.iterator;

import java.util.*;

/**
 * @author chenchao
 * @date 2021/11/8
 */
public class IteratorPattern {
    public static void main(String[] args) {
        Student student1 = new Student("小明");
        Student student2 = new Student("小王");

        Classroom classroom = new Classroom(2);
        classroom.addStudent(student1);
        classroom.addStudent(student2);

        ClassroomIterator iterator = classroom.iterator();
        while(iterator.hasNext()) {
            Student student = iterator.next();
            System.out.println(student);
        }
    }



    /**
     * 代表了一个集合类
     */
    public interface Aggregate {

        Iterator<Student> iterator();

    }

    /**
     * 学生类
     */
    public static class Student {

        private String name;

        public Student(String name) {
            this.name = name;
        }

        public String getName() {
            return name;
        }

        @Override
        public String toString() {
            return "Student [name=" + name + "]";
        }

    }

    /**
     * 教室迭代器
     * @author chenchao
     *
     */
    public static class ClassroomIterator implements Iterator {

        private Classroom classroom;
        private int index;

        public ClassroomIterator(Classroom classroom) {
            this.classroom = classroom;
            this.index = 0;
        }

        @Override
        public boolean hasNext() {
            if(index < classroom.getLength()) {
                return true;
            } else {
                return false;
            }
        }


        @Override
        public Student next() {
            Student student = classroom.getStudent(index);
            index++;
            return student;
        }

    }

    /**
     * 教室类
     * @author chenchao
     *
     */
    public static class Classroom implements Aggregate {


        private List<Student> students;

        /**
         * last相当于是数组的长度
         */
        private int last = 0;

        public Classroom(int size) {
            this.students = new ArrayList<Student>(2);
        }

        public Student getStudent(int index) {
            return students.get(index);
        }

        public void addStudent(Student student) {
            this.students.add(student);
            last++;
        }

        public int getLength() {
            return last;
        }

        /**
         * 返回一个教室迭代器，其中封装了教室自己，让迭代器可以获取教室中的数据
         */
        @Override
        public ClassroomIterator iterator() {
           //return students.iterator();
            return  new ClassroomIterator(this);
        }

    }
}
